import { defineStore } from "pinia";
import { ref, computed } from "vue";
import {useBindingStore} from "./useBindingStore";
import { useUserStore } from "./useUserStore.js";

// 修复导入方式
import { get, post } from "@/utils/request.js";

export const useAlertStore = defineStore("alert", () => {

  const bindingStore = useBindingStore();
  const userStore = useUserStore();

  // const role = userStore.getUserData?.role;
  // const userId = userStore.getUserData?.id;

  const alertUserId = ref(0);
  
  const setAlertUserId = (id)=> {
    alertUserId.value = id;
  };


  const alertList = ref([]);
  const getAlertList = computed(() => {
    return alertList.value;
  });

  const getAlertUserId = computed(() => {
    return alertUserId.value;
  });

  const setAlertUserIndex = (index) => {
    if (bindingStore) {
      alertUserId.value = bindingStore?.getBindingList[0].bindedId;
    }
  };

  // 从 API 拉取警报数据
  const fetchAlerts = async (userId) => {
    try {
      // 使用封装好的 get 方法
      if (!userId) {
        userId = alertUserId.value;
      }

      const res = await get(`/alerts/${userId}`, "api/v1");

      console.log("--fetchAlerts:", res);
      if (!res) {
        throw new Error("请求数据失败");
      } else if (res.code !== 200) {
        throw new Error(" 获取数据失败");
      }

      alertList.value = res.data
        .map((alert) => ({
          ...alert,
          type: alert.type || "normal",
          time: new Date(alert.triggerTime).toLocaleTimeString([], {
            hour: "2-digit",
            minute: "2-digit",
          }),
          message: alert.description,
          device: alert.triggeror || "未知设备",
        }))
        // 筛选resolved为false的警报
        .filter(alert => !alert.resolved)

      return res;
    } catch (error) {
      console.log("fetchAlert:", error);
      throw error;
    }
  };

  // 提交新警报到服务器
  const triggerAlert = async (alertData) => {
    try {
      console.log("triggerAlertData:", alertData);

      // 使用封装好的 post 方法
      const res = await post("/alerts/trigger", alertData, "api/v1", { method: 'POST' });

      if (!res) {
        throw new Error("请求数据失败");
      } else if (res.code !== 200) {
        throw new Error(" 获取数据失败");
      }

      //算了,懒得处理了,直接重新拉取数据吧
      await fetchAlerts();  

      return res;
    } catch (error) {
      console.log("triggerAlert Error:", error);
      throw error;
    }
  };

  // 标记警报为已处理
  const resolveAlert = async (id) => {
    try {
      console.log("resolveAlert:", id);
      const res = await post("/alerts/update", { alertID:id,status:true }, "api/v1", { method: 'POST' });

      console.log("resolveAlert:", res);
      if (!res) {
        throw new Error("请求数据失败");
      } else if (res.code !== 200) {
        throw new Error(" 获取数据失败");
      }
      console.log("resolveAlert:????", alertList.value);
      alertList.value = alertList.value.filter((a) => a.id !== id);
      console.log("resolveAlert:-----", alertList.value);


      return res;
    } catch (error) {
      console.log("resolveAlert Error:", error);
    }
  };
  // fetchAlerts();
  return {
    getAlertList,
    fetchAlerts,
    triggerAlert,
    resolveAlert,
    getAlertUserId,
    setAlertUserId,
    setAlertUserIndex,
  };
});
